<?php

/**
 * 新闻管理
 */

namespace app\avikcm\controller;

use think\Db;
use think\facade\Request;

class Article extends Common
{
    public function initialize()
    {
        parent::initialize();
    }


    // 新闻
    public function index()
    {
        if (Request::isAjax()) {
            $key = input('post.key');
            $type = input('post.type_id');
            $this->assign('testkey', $key);
            $page = input('page', 1);
            $pageSize = input('limit', config('pageSize'));
            $paginate = ['list_rows' => $pageSize, 'page' => $page];
            $list = db('article')->alias('a')->where('title', 'like', "%" . $key . "%")->order('update_time', 'desc')->paginate($paginate)->toArray();

            return ['code' => 0, 'msg' => '成功', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        return $this->fetch();
    }

    // 添加新闻
    public function add()
    {
        if (Request::isAjax()) {
            //构建数组
            $data = Request::except('file');
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['update_time'] = date('Y-m-d H:i:s');
            db('article')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '添加成功!';
            $result['url'] = url('index');
            return $result;
        } else {
            $this->assign('title', '添加内容');
            $this->assign('info', 'null');
            return $this->fetch('form');
        }
    }

    // 修改新闻
    public function edit()
    {
        if (Request::isAjax()) {
            //构建数组
            $data = Request::except('file');
            $data['update_time'] = date('Y-m-d H:i:s');
            db('article')->update($data);
            $result['code'] = 1;
            $result['msg'] = '修改成功!';
            $result['url'] = url('index');
            return $result;
        } else {
            $id = input('id');
            $info = db('article')->where('id', $id)->find();
            $this->assign('info', json_encode($info, true));
            $this->assign('baseInfo', $info);
            $this->assign('title', '修改内容');
            return $this->fetch('form');
        }
    }
    // 置顶新闻
    public function top()
    {
        $id = input('id');
        db('news')->where('id', $id)->update(['top' => 1]);
        $result['code'] = 1;
        $result['msg'] = '置顶成功!';
        return $result;
    }
    // 删除新闻
    public function del()
    {
        $id = input('id');
        db('article')->where('id', $id)->delete();
        return ['code' => 1, 'msg' => '删除成功！'];
    }
    // 批量删除新闻
    public function delAll()
    {
        $map[] = array('id', 'in', input('param.ids/a'));
        db('article')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        return $result;
    }

}
